import G6 from '@antv/g6';

//  节点和线active的操作，高亮+菜单
G6.registerBehavior('edge-active-result', {
  getDefaultCfg() {
    return {
      multiple: false,
      selected: [],
      start: {},
      end: {},
    };
  },
  getEvents() {
    return {
      'edge:click': 'onEdgeClick',
      'edge:contextmenu': 'onEdgeClick', // 右键线
      'canvas:mousedown': 'onCanvasDown', // 点击canvas触发
      'edge:mouseenter': 'onEdgeMouseEnter', // 监听事件 线mousemove，响应函数时 onEdgeMouseEnter
      'edge:mouseleave': 'onEdgeMouseLeave', // 监听事件 线mouseleave，响应函数时 onEdgeMouseLeave
    };
  },
  onCanvasDown(e) {
    // 取消掉所有的active节点和线
    this.inactiveAll();
  },

  // 隐藏节点菜单
  hiddenAllMenu() {
    if (this.edgeConextMenu) {
      this.edgeConextMenu.style.display = 'none';
    }
    if (this.nodeConextMenu) {
      this.nodeConextMenu.style.display = 'none';
    }
  },

  onEdgeClick(ev) {
    // 取消掉所有的active节点和线
    this.inactiveAll();

    // 展示node的菜单
    this.showEdgeMenu(ev);
  },

  // 展示线菜单
  showEdgeMenu(ev) {
    const model = ev.item.getModel();
    const { startPoint, endPoint, percent } = model;
    // 百分比，则返回
    if (percent) {
      return;
    }
    const x = startPoint.x > endPoint.x ? endPoint.x - 35 : endPoint.x;
    const y = endPoint.y / 3 + (2 / 3) * startPoint.y;
    this.edgeConextMenu = ev.currentTarget._edgeMenu;
    this.edgeConextMenu.setting = document.getElementById('edgeSetting');
    const pos = this.graph.getCanvasByPoint(x, y);
    this.edgeConextMenu.style.display = 'block';
    this.edgeConextMenu.style.left = pos.x + 'px';
    this.edgeConextMenu.style.top = pos.y + 'px';
    this.edgeConextMenu.id = ev.item._cfg.id;
  },

  inactiveAll() {
    this.hiddenAllMenu();
  },
  // 线的onEdgeMouseEnter
  onEdgeMouseEnter(ev) {
    const currentEdge = ev.item;
    this.graph.setItemState(currentEdge, 'compare', false);
    this.graph.setItemState(currentEdge, 'active', true);
  },
  onEdgeMouseLeave(ev) {
    const currentEdge = ev.item;
    const { color } = currentEdge.getModel();
    this.graph.setItemState(currentEdge, 'active', currentEdge.hasState('selected'));
    if (color === '_GREEN') {
      this.graph.setItemState(currentEdge, 'compare', true);
    }
  },
});
